package com.cloudcms.web.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CommUtil {
    /**
     * 最近一次生成令牌值的时间戳。
     */
    private static long previous;
    /**
     * 根据用户会话ID和当前的系统时间生成一个唯一的令牌。
     */
    public static synchronized String generateToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            byte id[] = session.getId().getBytes();
            long current = System.currentTimeMillis();
            if (current == previous) {
                current++;
            }
            previous = current;
            byte now[] = new Long(current).toString().getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(id);
            md.update(now);
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
    public static String getMd5Str(String username,String password) throws Exception {
        byte[] ar1 = username.getBytes();
        byte[] ar2 = password.getBytes();

        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(ar1);
        localMessageDigest.update(ar2);

        return toHex(localMessageDigest.digest());
    }
    /**
     * 将一个字节数组转换为一个十六进制数字的字符串。
     */
    public static String toHex(byte buffer[]) {
        StringBuffer sb = new StringBuffer(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }

}
